package tiltmaze.solver;

import java.util.HashMap;
import java.util.HashSet;
import tiltmaze.RowCol;

/**
 * Helper class used for generating the simple state graph.
 * @author Juraj Nižnan
 */
public class MazeMotionGraphInverted {

    HashMap<RowCol, VertexInverted> vertexMap = new HashMap<RowCol, VertexInverted>();

    public MazeMotionGraphInverted(MazeMotionGraph mmg) {
        for (Vertex v : mmg.vertices) {
            RowCol rc = new RowCol(v.position);
            VertexInverted vi = getVertex(rc);
            for (int i = 0; i < 4; i++) {
                if (v.targets[i] != null) {
                    RowCol rc1 = new RowCol(v.targets[i].position);
                    VertexInverted vi1 = getVertex(rc1);
                    vi1.sources.put(vi, getOptions(v.edges[i]));
                }
            }
        }
    }

    private VertexInverted getVertex(RowCol rc) {
        if (vertexMap.get(rc) == null) {
            vertexMap.put(rc, new VertexInverted(rc));
        }
        return vertexMap.get(rc);
    }

    private HashSet<Integer> getOptions(int ch) {
        HashSet<Integer> ret = new HashSet<Integer>();
        ret.add(0);
        int i = 1;
        int m = 0xFFFFFFF;
        while (i < m) {
            i = i * 2;
            ret.add((i - 1) & ch);
            ret.add((m - i + 1) & ch);
        }
        return ret;
    }
}
